import { getHttpEndpoint } from "@orbs-network/ton-access";
import { Address, SenderArguments, TonClient ,TonClient4 } from "@ton/ton"
import { useTonAddress, useTonConnectUI } from "@tonconnect/ui-react"
import { useEffect, useState } from "react"
import Counter from "../contracts/counter";

// 初始化TON客户端（测试网）
// const tonClient = new TonClient({
//   endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
// })


export const Counters = ()=>{

    const contractAddress = 'EQBYLTm4nsvoqJRvs_L-IGNKwWs5RKe19HBK_lFadf19FUfb'; // 示例合约地址
    const [myClient, setmyClient] = useState<any>()
    const [mycounterContract, setmyCounterContract] = useState<any>()
    
    const [counterValue, setCounterValue] = useState<string | null>(null);
    const address = useTonAddress()

    const [tonConnectUI] = useTonConnectUI();



    useEffect(()=>{
        if(!address) return
        readContractState()
    },[address])

    // 读取合约状态示例
    const readContractState = async () => {
      if (!address) return;

      // initialize ton rpc client on testnet 初始化TON客户端（测试网）
      const endpoint = await getHttpEndpoint({ network: "testnet" });
      const client = new TonClient({ endpoint });
      setmyClient(client)

      // open Counter instance by address读取合约  传入合约类(可以由后台获取)
      const counterAddress = Address.parse(contractAddress); // replace with your address from step 8
      const counter = new Counter(counterAddress);
      const counterContract = client.open(counter);
      console.log('counterContract-----计数合约---1')
      console.log(counterContract)
      setmyCounterContract(counterContract)

      // call the getter on chain 获取计数getCounter  方法1
      const counterValue = await counterContract.getCounter();
      console.log('获取计数getCounter-------1')
      console.log(counterValue)
      setCounterValue(counterValue.toString())

      try {
          //方法2
          const counterContract2 = client.open(new CounterContract(Address.parse(contractAddress),client));
          console.log('counterContract2-----------')
          console.log(counterContract2)
          const value2 = await counterContract2.getCounter();
          console.log(value2)


          console.log('runMethod直接请求------------')
          const result = await client.runMethod(counterAddress, 'counter');
          console.log(result.stack.readNumber())

      // console.log("value:", counterValue.toString());
      } catch (error) {
        console.error("获取合约失败:", error);
      }
      


      // 
      // try {
      //   const contract = tonClient.open(new CounterContract(Address.parse(contractAddress)));
      //   console.log('contract----')
      //   console.log(contract)
      //   const value = await contract.getCounterSS();
      //   setContractState(value);
      //   setError(null);
      // } catch (err) {
      //   setError('Failed to read contract state');
      //   console.error(err);
      // }
    };

    //点击发送
    const sendTon = async()=>{
      console.log(myClient)
      let sender = {
        send: async (args: SenderArguments) => {
          console.log('args-----')
          console.log(args)
          tonConnectUI.sendTransaction({
            messages: [
              {
                address: args.to.toString(),
                amount: args.value.toString(),
                payload: args.body?.toBoc().toString("base64"),
              },
            ],
            validUntil: Date.now() + 5 * 60 * 1000, // 5 minutes for user to approve
          });
        },
      };

      if(!myClient) return
      console.log('mycounterContract---合约')
      console.log(mycounterContract)
      try {
        await mycounterContract.sendIncrement(sender)
      } catch (error) {
        console.log(error)
      }

    }

    return <div>
        <p>合约地址: {contractAddress}</p>
        <p>读取调用智能合约-------------</p>
        <p>获取合约方法counter值:{counterValue}</p>
        <br />
        <p>向合约发送TON消息 改变counter值-------------</p>
        <button onClick={sendTon}>发送TON</button>
        {/* {contractState && (
            <div className="contract-state">
              <h3>Contract State:</h3>
              <pre>{JSON.stringify(contractState, null, 2)}</pre>
            </div>
          )}
        Counter */}
    </div>


}

// 智能合约抽象类示例
class CounterContract {
    constructor(public readonly address: Address,public provider: any) {}

    async getCounter() {
        try {
            const result = await this.provider.runMethod(this.address, 'counter')
            console.log('方法get_counter---')
            console.log(result)
            return result.stack.readNumber()
        } catch (error) {
            console.error("获取合约失败:", error);
        }
    }
}
